from django.contrib import admin
from .models import City, DataCenter, Host, HostCredential, HostStatistics, RequestLog


@admin.register(City)
class CityAdmin(admin.ModelAdmin):
    list_display = ['name', 'code', 'created_at']
    search_fields = ['name', 'code']
    list_filter = ['created_at']


@admin.register(DataCenter)
class DataCenterAdmin(admin.ModelAdmin):
    list_display = ['name', 'code', 'city', 'contact_person', 'contact_phone', 'created_at']
    search_fields = ['name', 'code', 'city__name']
    list_filter = ['city', 'created_at']
    raw_id_fields = ['city']


@admin.register(Host)
class HostAdmin(admin.ModelAdmin):
    list_display = ['hostname', 'ip_address', 'datacenter', 'status', 'os_type', 
                   'last_ping_result', 'last_ping_time', 'created_at']
    search_fields = ['hostname', 'ip_address', 'datacenter__name']
    list_filter = ['status', 'os_type', 'datacenter__city', 'last_ping_result', 'created_at']
    raw_id_fields = ['datacenter']
    readonly_fields = ['last_ping_time', 'last_ping_result']


@admin.register(HostCredential)
class HostCredentialAdmin(admin.ModelAdmin):
    list_display = ['host', 'username', 'password_updated_at', 'created_at']
    search_fields = ['host__hostname', 'username']
    list_filter = ['username', 'password_updated_at', 'created_at']
    raw_id_fields = ['host']
    exclude = ['encrypted_password']  # 不显示加密密码字段
    
    def has_change_permission(self, request, obj=None):
        # 限制密码修改权限
        return request.user.is_superuser


@admin.register(HostStatistics)
class HostStatisticsAdmin(admin.ModelAdmin):
    list_display = ['statistics_date', 'city', 'datacenter', 'total_hosts', 
                   'online_hosts', 'offline_hosts', 'maintenance_hosts']
    search_fields = ['city__name', 'datacenter__name']
    list_filter = ['statistics_date', 'city', 'datacenter']
    date_hierarchy = 'statistics_date'
    readonly_fields = ['created_at']


@admin.register(RequestLog)
class RequestLogAdmin(admin.ModelAdmin):
    list_display = ['created_at', 'method', 'path', 'status_code', 'duration_ms', 
                   'user', 'ip_address']
    search_fields = ['path', 'user__username', 'ip_address']
    list_filter = ['method', 'status_code', 'created_at']
    date_hierarchy = 'created_at'
    readonly_fields = ['created_at']
    
    def has_add_permission(self, request):
        # 禁止手动添加请求日志
        return False
    
    def has_change_permission(self, request, obj=None):
        # 禁止修改请求日志
        return False
